package com.ran.java_gobang_new.manager;

import com.ran.java_gobang_new.my_exception.GameException;
import com.ran.java_gobang_new.pojo.dao.Room;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-09-03
 * Time: 23:49
 */
@Configuration
public class RoomManager {
    // 房间号 id 与 房间 room 建立联系, 确保一个房间好对应一个房间
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    // 将 用户id 与 房间id 建立联系, 通过用户能找到房间号, 通过房间号又能找到房间
    private ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<>();

    public void add(Room room, Integer userId1, Integer userId2) {
        rooms.put(room.getUUID(),room);
        userIdToRoomId.put(userId1,room.getUUID());
        userIdToRoomId.put(userId2,room.getUUID());
    }

    public void remove(Room room,Integer userId1, Integer userId2) {
        rooms.remove(room.getUUID());
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }
    // 根据房间 id 获取 房间(可能用上)
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    // 根据用户 id 获取 房间(可能用上)
    public Room getRoomByUserId(Integer userId) {
        String roomId = userIdToRoomId.get(userId);
        if (roomId == null) {
            return null;
        }
        return rooms.get(roomId);
    }
}
